<template>
    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="600" :styles="{top: '30px'}">
        <Form ref="userForm" :model="userForm" :label-width="70" :rules="userFormValidate">
            <FormItem label="用户名" prop="userName">
                <Input v-model="userForm.userName" autocomplete="off"/>
            </FormItem>
            <FormItem label="密码" prop="password" v-if="modalType===0" :error="errorPass">
                <Input type="password" v-model="userForm.password" autocomplete="off"/>
            </FormItem>
            <FormItem label="邮箱" prop="email">
                <Input v-model="userForm.email"/>
            </FormItem>
            <FormItem label="手机号" prop="mobile">
                <Input v-model="userForm.mobile"/>
            </FormItem>
            <FormItem label="性别" prop="sex">
                <RadioGroup v-model="userForm.sex">
                    <Radio :label="1">男</Radio>
                    <Radio :label="0">女</Radio>
                </RadioGroup>
            </FormItem>
            <Form-item label="头像" prop="avatar">
                <Poptip trigger="hover" title="图片预览" placement="right" width="350">
                    <Input v-model="userForm.avatar" placeholder="可直接填入网络图片链接" clearable/>
                    <div slot="content">
                        <img :src="userForm.avatar" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
                        <a @click="viewPic()" style="margin-top:5px;text-align:right;display:block">查看原图</a>
                    </div>
                </Poptip>
                <Upload action="/xboot/upload/file"
                        :headers="accessToken"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :format="['jpg','jpeg','png','gif']"
                        :max-size="5120"
                        :on-format-error="handleFormatError"
                        :on-exceeded-size="handleMaxSize"
                        :before-upload="beforeUpload"
                        ref="up"
                        class="upload">
                    <Button icon="ios-cloud-upload-outline">上传图片</Button>
                </Upload>
            </Form-item>
            <Form-item label="所属部门" prop="deptName">
                <Poptip trigger="click" placement="right" title="选择部门" width="250">
                    <div style="display:flex;">
                        <Input v-model="userForm.deptName" readonly style="margin-right:10px;"/>
                        <Button icon="md-trash" @click="clearSelectDep">清空已选</Button>
                    </div>
                    <div slot="content">
                        <Tree :data="dataDep" :load-data="loadDataTree" @on-select-change="selectTree"></Tree>
                        <Spin size="large" fix v-if="deptLoading"></Spin>
                    </div>
                </Poptip>
            </Form-item>
            <FormItem label="用户类型" prop="userType">
                <Select v-model="userForm.userType" placeholder="请选择">
                    <Option :value="'UT_USER'">普通用户</Option>
                    <Option :value="'UT_SYS'">管理员</Option>
                </Select>
            </FormItem>
            <FormItem label="角色分配" prop="roleIds">
                <Select v-model="userForm.roleIds" multiple>
                    <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName">
                        <!-- <div style="display:flex;flex-direction:column"> -->
                        <span style="margin-right:10px;">{{ item.roleName }}</span>
                        <span style="color:#ccc;">{{ item.remark }}</span>
                        <!-- </div> -->
                    </Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelUser">取消</Button>
            <Button type="primary" :loading="submitLoading" @click="submitUser">提交</Button>
        </div>
    </Modal>
</template>

<script>
    import {addUser, editUser,loadDepartment, initDepartment} from "@/api/index";
    export default {
        name: "userAdd",
        data() {
            const validatePassword = (rule, value, callback) => {
                if (value.length < 6) {
                    callback(new Error("密码长度不得小于6位"));
                } else {
                    callback();
                }
            };
            const validateMobile = (rule, value, callback) => {
                var reg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error("手机号格式错误"));
                } else {
                    callback();
                }
            };
            return {
                accessToken: {},
                modalType: 0,
                errorPass: "",
                deptLoading: false,
                modalTitle: "",
                dataDep: [],
                userRoles: [],
                roleList: [],
                submitLoading: false,
                modalVisible: false,
                userForm: {
                    sex: 1,
                    userType: 'UT_USER',
                    avatar: "https://s1.ax1x.com/2018/05/19/CcdVQP.png",
                    roleIds: [],
                    departmentId: "",
                    deptName: ""
                },
                userFormValidate: {
                    userName: [
                        {required: true, message: "账号不能为空", trigger: "blur"}
                    ],
                    mobile: [
                        {required: true, message: "手机号不能为空", trigger: "blur"},
                        {validator: validateMobile, trigger: "blur"}
                    ],
                    email: [
                        {required: false, message: "请输入邮箱地址"},
                        {type: "email", message: "邮箱格式不正确"}
                    ]
                }
            }
        },
        methods: {
            init() {
                this.accessToken = {
                    accessToken: this.getStore("accessToken")
                };
                this.getParentList();
            },
            //添加-部门选择初始化
            getParentList() {
                initDepartment().then(res => {
                    if (res.status === true) {
                        this.dataDep = res.data;
                    }
                });
            },
            add() {
                this.modalTitle='添加用戶';
                this.$refs.userForm.resetFields();
                this.modalVisible = true;
            },
            edit() {
                this.modalTitle='编辑用戶';
                this.modalVisible = true;
            },
            cancelUser() {
                this.modalVisible = false;
            },
            viewPic() {
                this.viewImage = true;
            },
            clearSelectDep() {
                this.userForm.departmentId = "";
                this.userForm.deptName = "";
            },
            handleFormatError(file) {
                this.$Notice.warning({
                    title: "不支持的文件格式",
                    desc:
                    "所选文件‘ " +
                    file.name +
                    " ’格式不正确, 请选择 .jpg .jpeg .png .gif格式文件"
                });
            },
            handleMaxSize(file) {
                this.$Notice.warning({
                    title: "文件大小过大",
                    desc: "所选文件‘ " + file.name + " ’大小过大, 不得超过 5M."
                });
            },
            beforeUpload() {
                if (!this.$route.meta.permTypes.includes("upload")) {
                    this.$Message.error("此处您没有上传权限(为演示功能，该按钮未配置隐藏)");
                    return false;
                }
                return true;
            },
            handleSuccess(res, file) {
                if (res.success === true) {
                    file.url = res.result;
                    this.userForm.avatar = res.result;
                } else {
                    this.$Message.error(res.message);
                }
            },
            handleError(error, file, fileList) {
                this.$Message.error(error.toString());
            },
            selectTree(v) {
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let data = JSON.parse(JSON.stringify(v[0]));
                    this.userForm.departmentId = data.value;
                    this.userForm.deptName = data.label;
                }
            },
            submitUser() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            // 添加用户 避免编辑后传入id
                            delete this.userForm.id;
                            delete this.userForm.status;
                            if (
                                this.userForm.password == "" ||
                                this.userForm.password == undefined
                            ) {
                                this.errorPass = "密码不能为空";
                                return;
                            }
                            if (this.userForm.password.length < 6) {
                                this.errorPass = "密码长度不得少于6位";
                                return;
                            }
                            this.submitLoading = true;
                            addUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("添加成功");
                                    this.$parent.refreshTable();
                                    this.modalVisible = false;
                                }
                            });
                        } else {
                            // 编辑
                            editUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("修改成功");
                                    this.$parent.refreshTable();
                                    this.modalVisible = false;
                                }
                            });
                        }
                    }
                });
            },
            loadDataTree(item, callback) {
                loadDepartment(item.value).then(res => {
                    if (res.status === true) {
                        callback(res.data);
                    }
                });
            }
        },
        mounted() {
            this.init();
        }
    }
</script>

<style>

</style>